package cn.hr.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import cn.hr.pojo.SysRole;
import cn.hr.service.impl.SysRoleService;
import cn.hr.utils.PhoneIndustrySMS;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hr.utils.Constants;
import cn.hr.pojo.SysUser;
import cn.hr.service.SysUserService;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 *
 * @author MO
 */
@Controller
@RequestMapping("/user")
public class UserController {
    private Logger logger = LoggerFactory.getLogger(UserController.class);
    @Resource
    private SysUserService userService;
    @Resource
    private SysRoleService roleService;
    private String meagess;

    /**
     * 跳转到手机验证码页面
     * @return
     */
    @RequestMapping("/phone")
    public String phone(HttpSession session,Model model){
        model.addAttribute("phone",((SysUser) (session.getAttribute(Constants.USER_SESSION))).getPhone());
        return "user/phone";
    }

    /**
     * 发送验证码
     */
    @RequestMapping("/phoneOr")
    @ResponseBody
    public String phone(HttpSession session){
        PhoneIndustrySMS.to = ((SysUser) (session.getAttribute(Constants.USER_SESSION))).getPhone();//手机号码
        PhoneIndustrySMS.execute();//发送短信
        return "true";
    }

    @RequestMapping("/verify")
    @ResponseBody
    public String verify(@RequestParam("yun")String yun){
        if (yun.equals(PhoneIndustrySMS.code)){
            return "true";
        }else{
            return "false";
        }
    }

    /**
     * 验证旧密码是否正确
     *
     * @param pwd     旧密码
     * @param session
     * @return
     */
    @RequestMapping("/pwd")
    @ResponseBody
    public String pwd(@RequestParam(value = "pwd") String pwd, HttpSession session) {
        //使用springSecurity的BCryptPasswordEncoder加密
        SysUser user = null;
        try {
            meagess = "false";
            user = userService.get(((SysUser) (session.getAttribute(Constants.USER_SESSION))).getId());
            BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
            if (bc.matches(pwd,user.getPassword())) {//密码正确
                return "true";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return meagess;
    }


    /***
     * 按条件查询
     * @param _userName
     * @param _roleId
     * @param _oId
     * @param _pageIndex
     * @return
     */
    @RequestMapping("/showList")
    public String list(@RequestParam(value="name",required=false)String _userName,
                       @RequestParam(value="roleId",required=false)String _roleId,
                       @RequestParam(value="oId",required=false)String _oId,
                       @RequestParam(value="pageIndex",required=false)String _pageIndex,
                       Model model){
        Map<String,Object> map = new HashMap<>();

        System.out.print("oid:"+_oId);
        if (_userName != null&&_userName!="") map.put("name",_userName); model.addAttribute("name",_userName);
        if (_oId!=null&&_oId!="") map.put("oId",Integer.parseInt(_oId)); model.addAttribute("oId",_oId);
        if (_roleId!=null&&_roleId!="")map.put("roleId",Integer.parseInt(_roleId));model.addAttribute("roleId",_roleId);
        Integer index = 1;
        if (_pageIndex!=null&&_pageIndex!="")index = Integer.parseInt(_pageIndex);
        try {
            PageInfo<Map> pageInfo =  userService.findListByCondition(map,index);
            model.addAttribute("pageInfo",pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "user/showList";
    }

    @RequestMapping("/list")
    public String showList(){
        return "user/userList";
    }

    /**
     * 跳转到添加页面
     * @return
     */
    @RequestMapping("/userAdd")
    public String add(){
        return "user/userAdd";
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @RequestMapping("/userAddSave")
    public String addSave(@RequestParam("roleId")String roleId,SysUser user,HttpSession session){
        user.setCreatedById(1);
        //user.setCreatedById(((SysUser) (session.getAttribute(Constants.USER_SESSION))).getId());
        user.setCreatedDate(new Date());
        user.setRoleId(Integer.parseInt(roleId));
        try {
            user.setPassword(new BCryptPasswordEncoder().encode("1234"));//初始密码加密
            meagess = "redirect:userAdd";
            if (userService.insert(user)) {//添加用户
                meagess = "redirect:list";//跳到用户查询页面
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  meagess;
    }

    /**
     * 跳转到修改
     * @param _id
     * @return
     */
    @RequestMapping("/userUpdate")
    public String update(@RequestParam(value="id")String _id,@RequestParam(value="update",required = false)String update, Model model){
        SysUser user = null;
        if (update!=null&&update!=""){
            model.addAttribute("update",1);
        }else{
            model.addAttribute("update",0);
        }
        try {
            user = userService.get(Integer.parseInt(_id));
            int roleId = userService.getRoleIdByUserId(Integer.parseInt(_id));
            model.addAttribute("user",user);
            model.addAttribute("oId",user.getOId());
            model.addAttribute("roleId",roleId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  "user/userUpdate";
    }

    /**
     * 修改用户
     * @param user
     * @return
     */
    @RequestMapping("/userUpdateSave")
    public String updateSave(@RequestParam("roleId")String roleId,SysUser user,HttpSession session){
        user.setModifyById(((SysUser) (session.getAttribute(Constants.USER_SESSION))).getId());
        //user.setModifyById(1);
        user.setModifyDate(new Date());
        user.setRoleId(Integer.parseInt(roleId));
        try {
            meagess = "redirect:userUpdate?id="+user.getId();//跳转到修改页面
            if(userService.update(user)){
                meagess = "redirect:list";//跳到用户查询页面
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return meagess;
    }

    /**
     * 跳转到修改密码去
     * @return
     */
    @RequestMapping("/updatePwd")
    public String updatePwd(){
        return "user/pwd";
    }

    /**
     * 修改密码
     * @param pwd
     * @param session
     * @return
     */
    @RequestMapping("/updatePwdSave")
    public String updatePwdSave(@RequestParam("rpwd2")String pwd,HttpSession session){
        SysUser user = new SysUser();
        user.setPassword(new BCryptPasswordEncoder().encode(pwd));
        user.setId(((SysUser) (session.getAttribute(Constants.USER_SESSION))).getId());
        user.setModifyById(((SysUser) (session.getAttribute(Constants.USER_SESSION))).getId());
        user.setModifyDate(new Date());
        try {
            meagess = "redirect:updatePwd";//失败
            if (userService.update(user)){
                meagess = "redirect:/login";//修改成功跳转到登录界面
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return meagess;
    }

    /**
     * 删除
     * @param _id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String delete(@RequestParam(value="id")String _id){
        try {
            meagess = "false";
            if (userService.delete(Integer.parseInt(_id))){
                meagess = "true";
            }
        } catch (Exception e) {
            e.printStackTrace();
            meagess = "exception";
        }
        return meagess;
    }


    /**
     * 查询所有角色
     * @return
     */
    @RequestMapping("/role")
    @ResponseBody
    public Object roleList(){
        List<SysRole> roles = null;
        try {
            roles = roleService.findAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSON(roles);
    }

    @RequestMapping("/get")
    public String get(@RequestParam("id")String id,Model model){
        SysUser user = null;
        Integer roleId = null;
        try {
            user= userService.get(Integer.parseInt(id));
            roleId = userService.getRoleIdByUserId(Integer.parseInt(id));
            model.addAttribute("user",user);
            model.addAttribute("roleId",roleId);
            model.addAttribute("oId",user.getOId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "user/userSave";
    }
}

